package com.sh.secondhand;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.imageloader.BGAImage;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.github.ybq.android.spinkit.style.FadingCircle;
import com.google.gson.Gson;
import com.qiniu.android.utils.StringUtils;
import com.sh.Application.BaseApplication;
import com.sh.glide.BGAGlideImageLoader3;
import com.sh.struts.MoneyValueFilter;
import com.sh.utils.BackgroundManagerUtils;
import com.sh.utils.CommonStringUtils;
import com.sh.utils.FileUtils;
import com.sh.utils.Http.OkHttpUtils;
import com.sh.utils.Qiniu.QiniuUploadUtils;
import com.sh.utils.Utils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;

import static android.view.View.VISIBLE;

@RuntimePermissions
public class PublishProductActivity extends AppCompatActivity implements BGASortableNinePhotoLayout.Delegate, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private static final String TAG = "PublishProductActivity";
    private Boolean is_success = false;
    private static final int REQUEST_CODE_CHOOSE = 1013;
    private static final int RC_PHOTO_PREVIEW = 1014;
    private static final int PRODUCT_GENRE_CODE = 1015;

    /**
     * 拖拽排序九宫格控件
     */
    @BindView(R.id.snpl_moment_add_photos)
    BGASortableNinePhotoLayout mPhotosSnpl;

    ArrayList<String> imgPaths;

    @BindView(R.id.pro_genre_linear)
    LinearLayout productGenre;

    @BindView(R.id.pro_genre)
    TextView proGenre;
    @BindView(R.id.buy_way_self)
    Button buySelf;
    boolean buySelfBool = false;
    @BindView(R.id.buy_way_meet)
    Button buyMeet;
    boolean buyMeetBool = false;
    @BindView(R.id.buy_way_express)
    Button buyExpress;
    boolean buyExpressBool = false;
    @BindView(R.id.textView8)
    TextView saleWay;

    @BindView(R.id.express_free)
    CheckBox expressFree;
    @BindView(R.id.pro_express_fee)
    EditText proExpressFee;

    @BindView(R.id.pro_sale_price)
    EditText proSalePrice;
    @BindView(R.id.pro_buying_price)
    EditText proBuyingPrice;

    @BindView(R.id.pro_add_btn)
    Button proAdd;

    @BindView(R.id.pro_title)
    EditText proTitle;
    @BindView(R.id.pro_description)
    EditText proDescription;

    @BindView(R.id.pro_quality)
    EditText proQuality;

    @BindView(R.id.spin_kit)
    ProgressBar progressBar;

    @BindView(R.id.publish_relative)
    View relativeView;

    @BindView(R.id.publish_scroll)
    View scrollView;

    private Context context;

    private boolean isLocating = true;
    private String lat="";
    private String lng="";
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    lat = CommonStringUtils.safeString(aMapLocation.getLatitude());
                    lng = CommonStringUtils.safeString(aMapLocation.getLongitude());
                    isLocating = false;
                    //可在其中解析amapLocation获取相应内容。
                    Log.i(TAG,"locationinfo："+ aMapLocation.getLatitude()+" ,"+aMapLocation.getLongitude());
                    Log.i(TAG,"location: "+aMapLocation.getAddress());
                }else {
                    isLocating = false;
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_product);
        ButterKnife.bind(this);
        context = this;

        BGAImage.setImageLoader(new BGAGlideImageLoader3());
        mPhotosSnpl.setMaxItemCount(10);
        mPhotosSnpl.setEditable(true);
        mPhotosSnpl.setPlusEnable(true);
        mPhotosSnpl.setSortable(true);
        mPhotosSnpl.setItemSpanCount(4);
        // 设置拖拽排序控件的代理
        mPhotosSnpl.setDelegate(this);
        // 获取意图对象
        Intent intent = getIntent();
        //获取传递的值
        String str = intent.getStringExtra("img_path");
        imgPaths = new Gson().fromJson(str, ArrayList.class);
        mPhotosSnpl.setData(imgPaths);

        productGenre.setOnClickListener(this);

        proSalePrice.setFilters(new InputFilter[]{new MoneyValueFilter()});
        proBuyingPrice.setFilters(new InputFilter[]{new MoneyValueFilter()});
        proExpressFee.setFilters(new InputFilter[]{new MoneyValueFilter()});

        FadingCircle fadingCircle = new FadingCircle();
        progressBar.setIndeterminateDrawable(fadingCircle);

        proQuality.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (CommonStringUtils.safeInteger(charSequence.toString()) > 100) {
                    proQuality.setText("100");
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        PublishProductActivityPermissionsDispatcher.initGaodeWithPermissionCheck(this);
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        PublishProductActivityPermissionsDispatcher.openMatisseWithPermissionCheck(this);
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        mPhotosSnpl.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(this)
                .previewPhotos(models) // 当前预览的图片路径集合
                .selectedPhotos(models) // 当前已选中的图片路径集合
                .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                .currentPosition(position) // 当前预览图片的索引
                .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                .build();
        startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
    }

    @Override
    public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                List<String> result = Matisse.obtainPathResult(data);
                Set<String> resSet = new HashSet<>();
                resSet.addAll(mPhotosSnpl.getData());
                resSet.addAll(result);
                Log.i(TAG, result.toString());
                mPhotosSnpl.setData(new ArrayList<>(resSet));
            } else if (requestCode == RC_PHOTO_PREVIEW) {
                mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedPhotos(data));
            } else if (requestCode == PRODUCT_GENRE_CODE) {
                proGenre.setText(data.getStringExtra("pro_genre"));
            }
        }
    }

    /**
     * 打开Matisse的图片选择器
     */
    @NeedsPermission({Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void openMatisse() {
        Matisse.from(PublishProductActivity.this)
                .choose(MimeType.ofImage()) // 选择 mime 的类型
                .capture(true)  // 开启相机，和 captureStrategy 一并使用否则报错
                .captureStrategy(new CaptureStrategy(true, "com.sh.file.FileProviderImp")) // 拍照的图片路径
                .countable(true)
                .maxSelectable(mPhotosSnpl.getMaxItemCount() - mPhotosSnpl.getItemCount()) // 图片选择的最多数量
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f) // 缩略图的比例
                .imageEngine(new GlideEngine()) // 使用的图片加载引擎
                .forResult(REQUEST_CODE_CHOOSE); // 设置作为标记的请求码
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void deniedOpenMatisse() {
        showToastOnThread(this,"打开失败，没有对应的权限！");
    }

    @OnNeverAskAgain({Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA})
    void neverAskdeniedOpenMatisse() {
        showToastOnThread(this,"打开失败，请在权限管理中打开对应的权限");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PublishProductActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    @OnClick({R.id.buy_way_self, R.id.buy_way_meet, R.id.buy_way_express, R.id.pro_add_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pro_genre_linear: {
                startActivityForResult(new Intent(PublishProductActivity.this, ProductGenreChoiseActivity.class), PRODUCT_GENRE_CODE);
                break;
            }
            case R.id.buy_way_self: {
                if (buySelfBool) {
                    buySelf.setBackgroundResource(R.color.publish_sale_way_button_default);
                    buySelfBool = false;
                } else {
                    buySelf.setBackgroundResource(R.color.publish_sale_way_button_choose);
                    buySelfBool = true;
                }
                break;
            }
            case R.id.buy_way_meet: {
                if (buyMeetBool) {
                    buyMeet.setBackgroundResource(R.color.publish_sale_way_button_default);
                    buyMeetBool = false;
                } else {
                    buyMeet.setBackgroundResource(R.color.publish_sale_way_button_choose);
                    buyMeetBool = true;
                }
                break;
            }
            case R.id.buy_way_express: {
                if (buyExpressBool) {
                    buyExpress.setBackgroundResource(R.color.publish_sale_way_button_default);
                    buyExpressBool = false;
                } else {
                    buyExpress.setBackgroundResource(R.color.publish_sale_way_button_choose);
                    buyExpressBool = true;
                }
                break;
            }
            case R.id.pro_add_btn: {
                if (validate()) {
                    relativeView.setVisibility(View.GONE);
                    scrollView.setVisibility(View.GONE);
                    progressBar.setVisibility(VISIBLE);
                    new publishProduct().execute((Void) null);
                }
                break;
            }
            default: {
                break;
            }
        }
    }

    @Override
    @OnCheckedChanged({R.id.express_free})
    public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
        switch (compoundButton.getId()) {
            case R.id.express_free: {
                if (isChecked) {
                    proExpressFee.setText("0.00");
                    proExpressFee.setEnabled(false);
                } else {
                    proExpressFee.setEnabled(true);
                }
                break;
            }
            default:
                break;
        }
    }

    public boolean validate() {
        String title = proTitle.getText().toString();
        String description = proDescription.getText().toString();
        String imgCountWarn = "- 请选择大于一张图片\n";
        String genreWarn = "- 请选择正确的分类\n";
        String saleWayWarn = "- 请至少选择一种交易方式";
        String msg = "";

        if (StringUtils.isNullOrEmpty(title) || title.length() <= 5) {
            proTitle.setError("宝贝标题必须大于5个字符哦");
            proTitle.requestFocus();
            return false;
        }
        if (StringUtils.isNullOrEmpty(description) || description.length() <= 9) {
            proDescription.setError("宝贝描述必须大于等于10个字符哦");
            proDescription.requestFocus();
            return false;
        }
        if (StringUtils.isNullOrEmpty(proQuality.getText().toString())) {
            proQuality.setError("请输入宝贝成色");
            proQuality.requestFocus();
            return false;
        }
        if (CommonStringUtils.safeDouble(proSalePrice.getText().toString()) == 0) {
            proSalePrice.setError("请正确输入价格");
            proSalePrice.requestFocus();
            return false;
        }

        if (mPhotosSnpl.getItemCount() == 0) {
            msg += imgCountWarn;
        }
        if (StringUtils.isNullOrEmpty(proGenre.getText().toString()) || ">".equals(proGenre.getText().toString())) {
            msg += genreWarn;
        }
        if (!buyExpressBool && !buyMeetBool && !buySelfBool) {
            msg += saleWayWarn;
        }
        if (!StringUtils.isNullOrEmpty(msg)) {
            showDialog(R.mipmap.sorry, "提示", msg);
            return false;
        }
        if(isLocating){
            showToastOnThread(PublishProductActivity.this,"正在定位中，请稍后");
            return false;
        }
        return true;
    }

    private void showDialog(Integer iconId, String title, String message) {
        @SuppressWarnings("deprecation")
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_DayNight_Dialog_MinWidth);
        AlertDialog.Builder normalDialog =
                builder;
        normalDialog.setIcon(iconId);
        normalDialog.setTitle(title).setMessage(message);
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-
                    }
                });
        // 创建实例并显示
        normalDialog.create().show();
    }

    @NeedsPermission({Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE})
    void uploadProduct() {
        if(!Utils.checkLogin()){
            showToastOnThread(PublishProductActivity.this,"登录貌似失效了呢");
            return;
        }
        List<OkHttpUtils.Param> params = new ArrayList<>();
        params.add(new OkHttpUtils.Param("user_id", BaseApplication.getLoginInfo().getUserId().toString()));
        params.add(new OkHttpUtils.Param("title", proTitle.getText().toString()));
        params.add(new OkHttpUtils.Param("description", proDescription.getText().toString()));
        params.add(new OkHttpUtils.Param("integrity", proQuality.getText().toString()));
        params.add(new OkHttpUtils.Param("sale_price", proSalePrice.getText().toString()));
        params.add(new OkHttpUtils.Param("buy_price", proBuyingPrice.getText().toString()));
        params.add(new OkHttpUtils.Param("express_fee", proExpressFee.getText().toString()));
        params.add(new OkHttpUtils.Param("genre", proGenre.getText().toString()));
        params.add(new OkHttpUtils.Param("need_self", String.valueOf(buySelfBool)));
        params.add(new OkHttpUtils.Param("need_meet", String.valueOf(buyMeetBool)));
        params.add(new OkHttpUtils.Param("need_express", String.valueOf(buyExpressBool)));
        params.add(new OkHttpUtils.Param("lat",lat));
        params.add(new OkHttpUtils.Param("lng",lng));
        List<String> imgPaths = mPhotosSnpl.getData();
        File file = new File(getExternalFilesDir(null), "product" + File.separator + "images");
        if (!file.exists()) {
            file.mkdirs();
        }
        boolean res = false;
        List<String> paths = new ArrayList<>();
        try {
            for(String path : imgPaths) {
                String uploadPath = "product/images/show/" + BaseApplication.getLoginInfo().getUserId() + "_" + System.currentTimeMillis() + "." + FileUtils.getFileExt(imgPaths.get(0));
                AtomicReference<String> finalPath = new AtomicReference<>("");
                finalPath.set(QiniuUploadUtils.getInstance().syncUploadFile(new File(path), uploadPath));
                paths.add(finalPath.get());
            }
            StringBuilder stringBuilder = new StringBuilder();
            for(String path : paths){
                stringBuilder.append(path+",");
            }
            params.add(new OkHttpUtils.Param("images", stringBuilder.substring(0,stringBuilder.length()-1)));
            params.add(new OkHttpUtils.Param("show_img_path", paths.get(0)));
            String result = BackgroundManagerUtils.addProduct(params);
            if ("success".equals(result)) {
                is_success = true;
            }
            Log.i(TAG, stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class publishProduct extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            PublishProductActivityPermissionsDispatcher.uploadProductWithPermissionCheck(PublishProductActivity.this);
            return null;
        }

        @Override
        protected void onPostExecute(Void param) {
            super.onPostExecute(param);
            if (is_success) {
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    finish();
                });
            } else {
                runOnUiThread(() -> {
                    progressBar.setVisibility(View.GONE);
                    scrollView.setVisibility(VISIBLE);
                    relativeView.setVisibility(VISIBLE);
                    showToastOnThread(context, "上传失败，请检查网络后重试");
                });
            }
        }
    }

    /**
     * 在子线程里需要使用Toast
     *
     * @param context
     * @param message
     */
    private void showToastOnThread(Context context, String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @NeedsPermission({Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE})
    void initGaode(){
        //初始化定位
        mLocationClient = new AMapLocationClient(BaseApplication.getInstance());
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        //设置定位模式为AMapLocationMode.Battery_Saving，低功耗模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //给定位客户端对象设置定位参数
        if(null != mLocationClient){
            //设置定位回调监听
            mLocationClient.setLocationListener(mLocationListener);
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }else{
            Log.i(TAG,"Location is null");
        }
    }
}
